<?php

class MessagesController extends BaseController {
    
    private $userId;
    
    public function init() {
        parent::init();
        if(Yii::app()->user->isGuest) $this->redirect(array('default/login'));
        $this->userId = Yii::app()->user->getId();
    }
    
    public function actionMessages() {
        $model = new MessagesForm();
        if(isset($_POST['MessagesForm'])) {
            $model->attributes = $_POST['MessagesForm'];
            if($model->validate()) {
                $this->refresh();
            }
        }
        $count = Yii::app()->db->createCommand()->select('count(*)')->from('messages_dialogs d')->join('messages m', 'm.dialogId=d.dialogId and m.id=d.lastMessId and m.toId='.Yii::app()->user->getId())->where("(`user1Id`=$this->userId OR `user2Id`=$this->userId) AND (`user1Del`!=$this->userId AND `user2Del`!=$this->userId)")->queryScalar();
        $pagination = new CPagination($count);
        $pagination->setPageSize(Yii::app()->params['messages']['pagination']['perPage']);
        
        $dialogs = Yii::app()->db->createCommand()->select('d.*, m.*, u.login, u.avatar, u.displayName')->from('messages_dialogs d')->join('messages m', 'm.dialogId=d.dialogId and m.id=d.lastMessId and m.toId='.Yii::app()->user->getId())->leftJoin('users u', 'm.fromId=u.userId')->where("(`user1Id`=$this->userId OR `user2Id`=$this->userId) AND (`user1Del`!=$this->userId AND `user2Del`!=$this->userId)")->limit($pagination->getLimit(),$pagination->getOffset())->queryAll();
//        Hpr::pr($dialogs);
        $this->render('messages', array('model'=>$model, 'dialogs'=>$dialogs, 'pagination'=>$pagination));
    }
    
    public function actionOutbox() {
        $model = new MessagesForm();
        if(isset($_POST['MessagesForm'])) {
            $model->attributes = $_POST['MessagesForm'];
            if($model->validate()) {
                $this->refresh();
            }
        }
        $count = Yii::app()->db->createCommand()->select('count(*)')->from('messages_dialogs d')->join('messages m', 'm.dialogId=d.dialogId and m.id=d.lastMessId and m.fromId='.Yii::app()->user->getId())->where("(`user1Id`=$this->userId OR `user2Id`=$this->userId) AND (`user1Del`!=$this->userId AND `user2Del`!=$this->userId)")->queryScalar();
        $pagination = new CPagination($count);
        $pagination->setPageSize(Yii::app()->params['messages']['pagination']['perPage']);
        $dialogs = Yii::app()->db->createCommand()->select('d.*, m.*, u.login, u.avatar, u.displayName')->from('messages_dialogs d')->join('messages m', 'm.dialogId=d.dialogId and m.id=d.lastMessId and m.fromId='.Yii::app()->user->getId())->leftJoin('users u', 'm.toId=u.userId')->where("(`user1Id`=$this->userId OR `user2Id`=$this->userId) AND (`user1Del`!=$this->userId AND `user2Del`!=$this->userId)")->limit($pagination->getLimit(),$pagination->getOffset())->queryAll();
        $this->render('outbox', array('model'=>$model, 'dialogs'=>$dialogs, 'pagination'=>$pagination));
    }
    
    public function actionCapt() {
        $model = new MessagesForm();
        if(isset($_POST['MessagesForm'])) {
            $model->attributes = $_POST['MessagesForm'];
            if($model->validate()) {
                $this->refresh();
            }
        }
        $count = Yii::app()->db->createCommand()->select('count(*)')->from('messages_dialogs')->where("(`user1Id`=$this->userId OR `user2Id`=$this->userId) AND (`user1Del`=$this->userId OR `user2Del`=$this->userId)")->queryScalar();
        $pagination = new CPagination($count);
        $pagination->setPageSize(Yii::app()->params['messages']['pagination']['perPage']);
        #$dialogs = Yii::app()->db->createCommand()->select('d.*, m.*, u.login, u.avatar, u.displayName')->from('messages_dialogs d')->join('messages m', 'm.dialogId=d.dialogId and m.id=d.lastMessId')->leftJoin('users u', '(d.user1Id<>u.userId and d.user2Id = u.userId) or (d.user2Id<>u.userId and d.user1Id = u.userId)')->where("(`user1Id`=$this->userId OR `user2Id`=$this->userId) AND (`user1Del`=$this->userId OR `user2Del`=$this->userId)")->limit($pagination->getLimit(),$pagination->getOffset())->queryAll();
        $dialogs = Yii::app()->db->createCommand()->select('d.*, m.*')->from('messages_dialogs d')->join('messages m', 'm.dialogId=d.dialogId and m.id=d.lastMessId')->where("(`user1Id`=$this->userId OR `user2Id`=$this->userId) AND (`user1Del`=$this->userId OR `user2Del`=$this->userId)")->limit($pagination->getLimit(),$pagination->getOffset())->queryAll();
        if(!empty($dialogs)) {
            $idArr = array();
            for($i=0; $i<count($dialogs); $i++) {
                if($dialogs[$i]['fromId'] == $this->userId)
                    $idArr[] = $dialogs[$i]['toId'];
                else
                    $idArr[] = $dialogs[$i]['fromId'];
            }
            $users = Yii::app()->db->createCommand()->select('login, displayName, avatar, userId')->from('users')->where(array('in', 'userId', $idArr))->queryAll();
            for($i=0; $i<count($dialogs); $i++) {
                for($j=0; $j<count($users); $j++) {
                    if($dialogs[$i]['toId'] == $users[$j]['userId'] || $dialogs[$i]['fromId'] == $users[$j]['userId']) {
                        $dialogs[$i]['userFrom'] = $users[$j];
                    }
                }
            }
        }
        $this->render('capt', array('model'=>$model, 'dialogs'=>$dialogs, 'pagination'=>$pagination));
    }
    
    public function actionDialog($fromId, $toId) {
        $model = new MessagesForm();
        if(isset($_POST['MessagesForm'])) {
            $model->attributes = $_POST['MessagesForm'];
            if($model->validate()) {
                $this->refresh();
            }
        }
        $count = Yii::app()->db->createCommand()->select('count(*)')->from('messages')->where("fromId IN ( $fromId, $toId ) AND toId IN ( $fromId, $toId )")->queryScalar();
        $pagination = new CPagination($count);
        $pagination->setPageSize(Yii::app()->params['messages']['pagination']['perPage']);
        $mesData = Yii::app()->db->createCommand()->select('m.*')->from('messages m')->where('m.fromId IN ('. $fromId.','.$toId .') AND toId IN ('. $fromId.','.$toId.')')->order('sendDate DESC')->limit($pagination->getLimit(),$pagination->getOffset())->queryAll();
        $users = Yii::app()->db->createCommand()->select('avatar, login, displayName, userId')->from('users')->where(array('in', 'userId', array($fromId, $toId)))->queryAll();
        $dialog = Yii::app()->db->createCommand()->select('user1New,user2New, dialogId')->from('messages_dialogs')->where('dialogId='.$mesData[0]['dialogId'])->limit(1)->queryRow();
        if($dialog['user1New'] || $dialog['user2New']) {
            $fieldToUpdate = $dialog['user1New']==$this->userId ? 'user1New' : 'user2New';
            Yii::app()->db->createCommand()->update('messages_dialogs', array($fieldToUpdate=>'0'), 'dialogId='.$dialog['dialogId']);
        }
        Yii::app()->user->setReturnUrl(array('messages/dialog', 'fromId'=>$fromId, 'toId'=>$toId));
        $this->render('dialog', array('mesData'=>$mesData, 'users'=>$users, 'model'=>$model, 'pagination'=>$pagination, 'companion'=>$fromId==$this->userId ? $toId : $fromId));
    }
    
    public function actionDelDialog($dialogId) {
        $model = Dialogs::model()->findByPk($dialogId);
        if(!$model || $model->user1Del == $this->userId || $model->user2Del == $this->userId) 
            throw new CHttpException(404, 'Не найдено указанной записи');
        
        if($model->user1Del == 0) $col = 'user1Del';
        else if($model->user2Del == 0) $col = 'user2Del';
        
        Yii::app()->db->createCommand()->update('messages_dialogs', 
            array($col=>$this->userId), 'dialogId=:id', array(':id'=>$dialogId));
        
        $this->redirect(array('messages/messages'));
    }
    
    public function actionRenewDialog($dialogId) {
        $model = Dialogs::model()->findByPk($dialogId);
        if(!$model || ($model->user1Del != $this->userId && $model->user2Del != $this->userId) ) 
            throw new CHttpException(404, 'Не найдено указанной записи');  
        
        if($model->user1Del == $this->userId) $col = 'user1Del';
        else if($model->user2Del == $this->userId) $col = 'user2Del';
        
        Yii::app()->db->createCommand()->update('messages_dialogs', 
            array($col=>0), 'dialogId=:id', array(':id'=>$dialogId));
        
        $this->redirect(array('messages/capt'));
    }
    
    public function actionDelMessage($id) {
        Yii::app()->db->createCommand()->update('messages', array('message'=>'<span style="color:gray">Сообщение было удалено</span>'), 'id='.$id.' and fromId='.Yii::app()->user->getId());
        $this->redirect(Yii::app()->user->returnUrl);
    }
}